﻿using BuyWithoutLoseMoney;
using BuyWithoutLoseMoney.Core.Models;
using BuyWithoutLoseMoney.Core.Repositories;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using System.Threading.Tasks;

namespace BuyWithoutLose.Areas.Admin.Controllers
{
    /// <summary>
    /// 角色权限
    /// </summary>
    [Area("Admin")]
    
    public class RolePermissionController : BaseAdminController
    {
        private readonly IRepository<LoginUser, int> _loginUserRepository;
        private readonly IRepository<LoginUserRole, int> _loginUserRoleRepository;
        private readonly IRepository<Role, int> _roleRepository;
        private readonly IRepository<PermissionRole, int> _rolePermissionRepository;
        private readonly IRepository<Permission, int> _permissionRepository;
        private readonly IRepository<PermissionType, int> _permissionTypeRepository;
        private readonly BuyWithoutLoseMoneyDBContext db;

        public RolePermissionController(IRepository<LoginUser, int>loginUser, 
            IRepository<LoginUserRole, int> loginUserRole,
            IRepository<Role, int> role, 
            IRepository<PermissionRole, int> rolePermission, 
            IRepository<Permission, int> permission,
            IRepository<PermissionType, int> permissionType,
            BuyWithoutLoseMoneyDBContext buyWithoutLoseMoneyDBContext):base(buyWithoutLoseMoneyDBContext)
        {
            _loginUserRepository = loginUser;
            _loginUserRoleRepository = loginUserRole;
            _roleRepository = role;
            _rolePermissionRepository = rolePermission;
            _permissionRepository = permission;
            _permissionTypeRepository = permissionType;
            db = buyWithoutLoseMoneyDBContext;
        }
        /// <summary>
        /// 角色权限列表
        /// </summary>
        /// <returns></returns>
         //[HttpGet]
        public IActionResult Index()
        {
            var role = _roleRepository.GetAllList();
            ViewBag.Role = role;
            return View();
        }
        [HttpPost]
        public async Task<IActionResult> Index(int page, int limit,int roleid=0)
        {

            var rolePermission = _rolePermissionRepository.GetAll();
            var query = rolePermission.Include("Role").Include("Permission").Where(x => true);
            if (roleid!=0)
            {
                query = query.Where(x => x.RoleId == roleid);
            }
            var count = query.Count();
            var list = query.Skip((page - 1) * limit).Take(limit).ToList()
               .Select(x => new
               {
                   //id = x.Id,
                   role = x.Role.Name,
                   permission = x.Permission.Ext1
               });
            return Json(new { Code = 0, Msg = "", Data = list, Count = count });
        }
    }
}
